package yunplus.io.hchome.presenter.implement;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import im.fir.sdk.FIR;
import im.fir.sdk.VersionCheckCallback;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import yunplus.io.hchome.display.activity.WebviewActivity;
import yunplus.io.hchome.display.view.ICheckVersionView;
import yunplus.io.hchome.presenter.contract.ICheckVersionPresenter;
import yunplus.io.hchome.utils.HandlerUtils;
import yunplus.io.hchome.utils.ICallback;
import yunplus.io.hchome.utils.NetworkUtils;

/**
 * Created by yfsoft on 2016/12/18.
 */

public class CheckVersionPresenter implements ICheckVersionPresenter {

    private final static String TAG = "CheckVersionPresenter";

    private Activity _mActivity;

    private ICheckVersionView _mView;

    public CheckVersionPresenter(Activity activity, ICheckVersionView view) {
        this._mActivity = activity;
        this._mView = view;
    }


    @Override
    public void checkVersion(@NonNull String appkey) {
        _mView.onStartCheck();

        NetworkUtils.ping("www.baidu.com", new ICallback() {
            @Override
            public void onStart() {}

            @Override
            public void onSuccess(Object data) {
                FIR.checkForUpdateInFIR("21ccf6e7112469053d4aa7d6ca47187f", new VersionCheckCallback() {

                    JSONObject data;
                    @Override
                    public void onSuccess(String versionJson) {
                        Log.i(TAG, "check from fir.im success! " + "\n" + versionJson);
                        data = JSONObject.parseObject(versionJson);

                    }

                    @Override
                    public void onFail(Exception exception) {
                        Log.e(TAG, "check fir.im fail! " + "\n" + exception.getMessage());
                        _mView.onFinishCheck();
                    }

                    @Override
                    public void onStart() {}

                    @Override
                    public void onFinish() {
                        //error handler
                        Log.d(TAG, "onFinish");
                        String versionName = getVersionName();
                        if(versionName.equals(data.getString("versionShort"))){
                            _mView.onFinishCheck();
                        }else{
                            _mView.onFinishCheck(data);
                        }
                    }
                });
            }

            @Override
            public void onError(Object error) {
                _mView.onFinishCheck();
            }

            @Override
            public void onFinish() {

            }
        });

    }

    private String getVersionName(){
        // 获取packagemanager的实例
        PackageManager packageManager = _mActivity.getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo ;
        try {
            packInfo = packageManager.getPackageInfo(_mActivity.getPackageName(),0);
        } catch (PackageManager.NameNotFoundException e) {
            return "0";
        }
        String version = packInfo.versionName;
        return version;
    }
    @Override
    public void updateVersion(String uri, final String savePath) {

        _mView.onStartUpdate();

        OkHttpClient mOkHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(uri).build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                _mView.onUpdateError(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) {
                InputStream inputStream = response.body().byteStream();
                FileOutputStream fileOutputStream;
                try {
                    fileOutputStream = new FileOutputStream(new File(savePath));
                    byte[] buffer = new byte[2048];
                    int len = 0;
                    while ((len = inputStream.read(buffer)) != -1) {
                        fileOutputStream.write(buffer, 0, len);
                    }
                    fileOutputStream.flush();
                    fileOutputStream.close();
                    inputStream.close();
                    _mView.onFinishUpdate();
                } catch (IOException e) {
                    Log.e(TAG, e.getMessage());
                    _mView.onUpdateError(e.getMessage());
                }

            }
        });

    }

    @Override
    public void installVersion(@NonNull String savePath) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(savePath)),
                "application/vnd.android.package-archive");
        _mActivity.startActivity(intent);
    }

}
